/**
 * @file state_machine.c
 * @brief 通用状态机框架实现
 */
#include "state_machine.h"
#include <string.h>

void state_machine_init(StateMachine* fsm, const StateDef* states, 
                       uint8_t count, int initial_state) {
    if (fsm == NULL || states == NULL || count == 0) return;
    
    memset(fsm, 0, sizeof(StateMachine));
    fsm->states = states;
    fsm->state_count = count;
    fsm->current_state = initial_state;
    fsm->target_state = initial_state;
    fsm->is_changing = false;
}

void state_machine_set_target(StateMachine* fsm, int target) {
    if (fsm == NULL || target >= fsm->state_count) return;
    fsm->target_state = target;
    fsm->is_changing = true;
}

int state_machine_get_current(StateMachine* fsm) {
  return (fsm != NULL) ? fsm->current_state:0;
}

void state_machine_process(StateMachine* fsm) {
    if (fsm == NULL || fsm->states == NULL) return;
    
    // 处理状态切换
    if (fsm->is_changing && fsm->current_state != fsm->target_state) {
        // 调用当前状态的退出函数
        if (fsm->states[fsm->current_state].exit != NULL) {
            fsm->states[fsm->current_state].exit();
        }
        
        // 更新当前状态
        fsm->current_state = fsm->target_state;
        
        // 调用新状态的进入函数
        if (fsm->states[fsm->current_state].enter != NULL) {
            fsm->states[fsm->current_state].enter();
        }
        
        fsm->is_changing = false;
    }
    
    // 调用当前状态的处理函数
    if (fsm->states[fsm->current_state].process != NULL) {
        fsm->states[fsm->current_state].process();
    }
}
    